package com.bigboss.knowstar.service.impl;

import com.aliyun.oss.model.ObjectMetadata;
import com.bigboss.knowstar.exception.FileUploadException;
import com.bigboss.knowstar.service.IUploadService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import static com.bigboss.knowstar.utils.AliyunOssUtil.ossUploadFile;

@Service
public class OSSUploadServiceImpl implements IUploadService {

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");

    @Override
    public String uploadFile(MultipartFile file, HttpServletRequest req, String type) {
        try {
            if (file == null || file.isEmpty()) {
                throw new FileUploadException("文件为空，无法上传");
            }
            String originalFilename = file.getOriginalFilename();
            String format = sdf.format(new Date());
            String newFileName = type + "/" + format + UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
            return ossUploadFile(newFileName, file.getInputStream(), null);
        } catch (IOException e) {
            throw new FileUploadException("文件上传失败", e);
        }
    }

    @Override
    public List<String> multiUploadFiles(MultipartFile[] files, HttpServletRequest req, String type) {
        List<String> filePaths = new ArrayList<>();
        for (MultipartFile file : files) {
            if (file == null || file.isEmpty()) {
                throw new FileUploadException("文件为空，无法上传");
            }
            filePaths.add(uploadFile(file, req, type));
        }
        return filePaths;
    }
}
